package cn.edu.zzuli;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Date: 2021/3/8 20:14
 * @Author: 绯色下午茶
 * @Description:
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public   void put(String key, Object Value) throws InterruptedException {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t 写入 " + key);
            Thread.sleep(300);
            map.put(key, Value);
            System.out.println(Thread.currentThread().getName() + "\t 写入完成");
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "\t 读取 ");
        map.get(key);
        System.out.println(Thread.currentThread().getName() + "\t 读取完成 " + key);
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {

        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    myCache.put(finalI + "", finalI + "");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, "" + i).start();
        }
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.get(finalI + "");

            }, "" + i).start();
        }
    }
}
